<template>


  <div class="common-layout" :style="{height:'100%'}">
      <el-container>
          <el-header>
              <div class="title">
                  <h2>部门管理</h2>
                  <el-breadcrumb separator="/">
              </el-breadcrumb>
           </div>
          </el-header>
          
          <el-main>
            <el-row :gutter="10">
              <el-col :span="4" :offset="0"><el-input v-model="searchInput" placeholder="请输入部门名称"></el-input></el-col>
              <el-col :span="2.3" :offset="0"><el-button @click="searchNodes(state.tableData,searchInput)" type="primary" icon='search'>查询</el-button></el-col>
              <el-col :span="2.3" :offset="0"><el-button @click="addDepartment" type="success" icon='document'>添加部门</el-button></el-col>
              <el-col :span="2" :offset="0"><el-button @click="refreshData" plain icon='refresh'>重置</el-button></el-col>
            </el-row>
            <el-table
              :data="state.tableData"
              style="width: 100%; margin-bottom: 20px;height: 100%;;margin-top: 20px;"
              row-key="_id"
              
              default-expand-all
            >
            
            <el-table-column type="index" width="50" />
            <el-table-column prop="name" label="部门名称" sortable />
              <el-table-column prop="createdAt" label="创建时间" sortable :formatter="formatDate" />
              <el-table-column prop="updatedAt" label="修改时间" sortable :formatter="formatDate"/>
              <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button link type="primary" size="small"  @click="handleClick('detail',scope.$index, scope.row)"
                  >详细</el-button
                >
                <el-button link type="primary" size="small"  @click="handleClick('edit',scope.$index, scope.row)">修改</el-button>
              </template>
            </el-table-column>
            </el-table>

              <el-pagination
              v-model:current-page="state.currentPage"
              v-model:page-size="state.pageSize"
              :page-sizes="[5,10 , 30, 50,state.tableData.length]"
  
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.tableData.length"
           
              @current-change="handleCurrentChange"
              />
          </el-main>

          <div>
  

 </div>

      </el-container>

      <el-dialog
      width="40%"
      align-center
      title="新增部门"
      v-model="dialogVisible">
        

          <el-form v-model="state.newDepartmentForm">
           

            <el-row :gutter="24">
            <el-col :span="16">
              <el-form-item label="一级部门">
              <el-select v-model="state.newDepartmentForm.fatherDepartment"  
              :disabled="isTopDepartment"
              clearable
              style="width:100%" placeholder="选择上级部门，如是顶级部门则不选择">
              <el-option
                v-for="item in state.tableData"
                :key="item.name"
                :label="item.name"
                :value="item._id"
              />
            </el-select>
            </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="一级部门">
                <el-switch
                    v-model="isTopDepartment"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                  />
              </el-form-item>
            </el-col>
          </el-row>


            <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="部门名称">
                  <el-input v-model="state.newDepartmentForm.name" placeholder="输入新增部门名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总负责人">
                <el-input v-model="state.newDepartmentForm.departmentCreater" placeholder="输入新增部门负责人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="联系号码">
                  <el-input v-model="state.newDepartmentForm.departmentPhoneNumber"  placeholder="输入联系人号码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系邮箱">
                <el-input v-model="state.newDepartmentForm.departmentEmail"  placeholder="输入联系人邮箱"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="部门描述">
            <el-input
              v-model="state.newDepartmentForm.departmentDescription"
              :autosize="{ minRows: 3, maxRows: 4 }"
              type="textarea"
              placeholder="此处输入部门职能描述"
            />
          </el-form-item>
          </el-form>

          <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sumbitAddDepartment">
          确认新增
        </el-button>
      </span>
    </template>
      </el-dialog>

      <el-dialog
      width="40%"
      align-center
      :title=dialogOperationType
      v-model="dialogOperationVisible">
      <el-form v-model="state.detailRowData">

           <el-row :gutter="20">
           <el-col :span="10">
             <el-form-item label="部门名称">
                 <el-input v-model="state.detailRowData.name" 
                 :disabled="dialogOperationType!='编辑部门' ? true:false"
                  placeholder="输入新增部门名称"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="总负责人">
               <el-input 
               :disabled="dialogOperationType!='编辑部门' ? true:false"
               v-model="state.detailRowData.departmentCreater" placeholder="输入新增部门负责人"></el-input>
             </el-form-item>
           </el-col>
         </el-row>

         <el-row :gutter="20">
           <el-col :span="10">
             <el-form-item label="联系号码">
                 <el-input
                 :disabled="dialogOperationType!='编辑部门' ? true:false"
                 v-model="state.detailRowData.departmentPhoneNumber"  placeholder="输入联系人号码"></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="联系邮箱">
               <el-input 
               :disabled="dialogOperationType!='编辑部门' ? true:false"
               v-model="state.detailRowData.departmentEmail"  placeholder="输入联系人邮箱"></el-input>
             </el-form-item>
           </el-col>
         </el-row>

         <el-form-item label="部门描述">
           <el-input
            :disabled="dialogOperationType!='编辑部门' ? true:false"
             v-model="state.detailRowData.departmentDescription"
             :autosize="{ minRows: 3, maxRows: 4 }"
             type="textarea"
             placeholder="此处输入部门职能描述"
           />
         </el-form-item>
         </el-form>

         <template #footer>
     <span class="dialog-footer">
       <el-button @click="dialogOperationVisible = false">取消</el-button>
       <el-button type="primary" v-if="dialogOperationType == '编辑部门'" @click="sumbitEditDepartment">
         确认修改
       </el-button>
     </span>
     </template>
      </el-dialog>
  </div>



</template>

<script setup>


import { ElNotification } from 'element-plus';
import { reactive,ref,onMounted } from 'vue'
import requestMethods from '../../../api/api';

const dialogOperationType = ref()
const dialogOperationVisible = ref(false)
const dialogVisible = ref(false)
const searchInput = ref()
const isTopDepartment = ref(false)
const state = reactive({
detailRowData:{},
currentPage: 1,
pageSize: 10,
small: false,
background: false,
disabled: false,
tableData :[],
newDepartmentForm:{
  fatherDepartment:null
},
departmentEditForm:{}
})

onMounted(()=>{
  requestMethods.getAllDepartments().then(res=>{
    console.log(res.data);
    state.tableData = res.data
  }).catch(err=>{
    console.log(err);
  })
})


const sumbitEditDepartment = () =>{
 state.departmentEditForm = JSON.parse(JSON.stringify(state.detailRowData))
 requestMethods.updateDepartmentInfo(state.departmentEditForm,state.departmentEditForm._id)
 .then(res=>{
  console.log(res);
  ElNotification({
      title:'操作成功',
      type:'success'
    })
 }).catch(err=>{
  console.log(err);
  ElNotification({
      title:'似乎发生了一些错误···',
      type:'error',
      message:err.data.message
    })
 })
 console.log(state.departmentEditForm);
}

const handleClick = (type,index,row) => {
    if(type == 'edit'){
      dialogOperationType.value = '编辑部门'
    }else{
      dialogOperationType.value = '详情'
      state.departmentEditForm = row
    }
    dialogOperationVisible.value = true
    state.detailRowData = row
    console.log(index,state.detailRowData);
}


const addDepartment = () =>{
  dialogVisible.value = true
}
const sumbitAddDepartment = () =>{
  
  if(isTopDepartment.value){
    console.log("生成顶级");
    requestMethods.addDepartment(state.newDepartmentForm).then(res=>{
    console.log(res);
    ElNotification({
      title:'操作成功',
      type:'success'
    })
    state.tableData.push(res.data)
    dialogVisible.value = false
  }).catch(error=>{
    console.log(error);
  })
  }else{
    console.log("生成次级");
    requestMethods.addChildrenDepartment(state.newDepartmentForm,state.newDepartmentForm.fatherDepartment)
    .then(res=>{
      ElNotification({
      title:'操作成功',
      type:'success'
    })
    for(const node of state.tableData){
      if(node._id == (state.newDepartmentForm.fatherDepartment)){
        node.children.push(res.data)
      }
    }
    dialogVisible.value = false
    }).catch(err=>{
      console.log(err);
    })

  }
}
const searchNodes = (rootNode) =>{
  const results = [];
  const kw = searchInput.value
  for(const node of rootNode){
    if(node.name.includes(kw)){
      results.push(node)
      continue;
    }
    if(node.children && node.children.length > 0){
        for(const childrenNode of node.children){
          if(childrenNode.name.includes(kw)){
            results.push(childrenNode)
          }
        }
    }
  }
  
  state.tableData = results
}

const refreshData = () =>{
  requestMethods.getAllDepartments().then(res=>{
    console.log(res);
    state.tableData = res.data
  }).catch(err=>{
    console.log(err);
  })
}

const formatDate = (row, column, cellValue) =>{
  const date = new Date(cellValue)
      const year = date.getFullYear()
      const month = ('0' + (date.getMonth() + 1)).slice(-2)
      const day = ('0' + date.getDate()).slice(-2)
      const hours = ('0' + date.getHours()).slice(-2)
      const minutes = ('0' + date.getMinutes()).slice(-2)
      const seconds = ('0' + date.getSeconds()).slice(-2)
      return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}
const handleCurrentChange = (val) => {
  state.currentPage = val
  console.log(val);
}

</script>

<style scoped lang="less">
.el-container {

  --el-header-height:auto;
  
  .el-header {

    
      
   

      .title{

          display: flex;
          justify-content: flex-start;
     
          align-items: center;

          h2{
       
              border: 0;
             
              line-height: 40px;
          }
          .el-breadcrumb{
          padding-left: 20px;
          
      }
      }
     
  }

  .el-main {
      margin: 0;
      margin-top: 20px;
      height: 80vh;
      background-color: #ffff;
      border-radius: 25px 0px 0 0;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .el-pagination{
          padding-top: 20px;
      }
  }
}
</style>